<template>
    <el-upload
        :drag="!$slots.default"
        class="upload-demo"
        ref="upload"
        :action="$staticUrl"
        :show-file-list="false"
        :accept="accept"
        :data="uploadData"
        :on-success="onSuccess"
        :before-upload="_beforeUpload"
        :on-progress="progress"
    >
        <template v-if="isProgress && progressShow">
            <div class="progress-box">
                <el-progress :percentage="percentage" ></el-progress>
                <p>正在上传...</p>
            </div>
        </template>
        <template v-else>
            <slot></slot>
            <template v-if="!$slots.default">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">点击或拖拽文件上传</div>
            </template>
        </template>


    </el-upload>
</template>

<script lang="ts">
import { Component, Prop, Mixins } from "vue-property-decorator";
import { getUUID } from "@/utils";
import AuthMixin from "@/components/upload-cos/auth.mixin";
@Component({})
export default class UpLoadNormal extends Mixins(AuthMixin) {
    @Prop({ type: String, default: "" }) action!: string

    @Prop({
        type: Function,
        default: () => {
            return Promise.resolve(true);
        }
    })
    readonly beforeUpload!: any;

    @Prop({
        type: String,
        default: () => {
            return "*";
        }
    })
    readonly accept!: any;

    @Prop({
        type: String,
        default: 'temporary'
    })
    readonly type!: string


    @Prop({
        type: Boolean,
        default: true
    })
    readonly progressShow!: boolean


    @Prop({
        type: Number,
        default: 100
    })
    readonly max!: number

    path = ""
    formName = ''

    uploadData: any = {
        signature: '',
        "x-cos-security-token": "",
        "Content-Type": "",
        key: "",
        dir: "",
        host: ""
    };

    isProgress= false
    percentage= 50.66

    async onSuccess() {
        this.isProgress = false;
        // 拖拽上传
        if (!this.$slots.default) {
            this.$emit("onSuccess", {
                path: this.uploadData.key,
                formName: this.formName
            });
        // 正常上传
        } else {
            this.$emit("onSuccess", {
                path: this.uploadData.key,
                formName: this.formName,
                src: this.uploadData.host + this.uploadData.key
            });
        }
    }

    _beforeUpload(file: any) {
        return new Promise((resolve: any, reject: any) => {
            const maxSize = this.max * 1024 * 1024;
            if (file.size > maxSize) {
                this.$message.error(`上传文件大小请勿超过${this.max}M!`);
                reject(`上传文件大小请勿超过${this.max}M!`);
            }
            const uploadPolicy = () => {
                const videoList = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
                const radioList = ["wmv", "act", "rec", "vy1", "vy2", "vy3", "vy4", "sc4", "dvf", "msc", "wma", "mp3", "wav", "aiff", "ava", "m4a"];
                const imgList = ["bmp", "jpg", "jpeg", "png", "gif"];
                const docList = ["txt", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "htm", "html", "xml", "psd", "wps", "reg", "bat", "tmp", "log"];
                const arr = file.name.split(".");
                const fileType = arr[arr.length - 1];
                const type = videoList.includes(fileType) ? "video" : radioList.includes(fileType) ? "audio" : imgList.includes(fileType) ? "img" : docList.includes(fileType) ? "doc" : "other";

                const _path = `/${this.type}/${type}/${new Date().format("yyyy-MM-dd")}/${this.path}`;
                this.getAuthorization({ Method: 'POST', Pathname: '/' })
                    .then((info: any) => {
                        const uploadData: any = {};
                        uploadData.signature = info.Authorization;
                        uploadData['x-cos-security-token'] = info.XCosSecurityToken;
                        uploadData['Content-Type'] = "";
                        uploadData.key = _path + getUUID() + "." + fileType;
                        uploadData.dir = _path;
                        uploadData.host = this.$staticUrl;
                        this.uploadData = uploadData;
                        this.formName = file.name;
                        resolve(true);
                    })
                    .catch((err: any) => {
                        this.$message.error({
                            message: err.message || err.content || "接口请求失败",
                            type: "error",
                            duration: 1500
                        });
                        return reject(new Error(err));
                    });
            };
            uploadPolicy();
        });
    }


    progress(data: any, file: any) {
        if (!this.progressShow) {
            return false;
        }
        this.isProgress = true;
        this.percentage = Number(file.percentage.toFixed(0));
    }
}
</script>

<style lang="scss" scoped>
.progress-box{
    width: 100%;
    max-width: 300px;
}

.upload-demo{
    width: 100%!important;
}

::v-deep{
    .el-upload{
        text-align: left;
    }
}
</style>
